import os
import json
from openai import OpenAI

class StoryGenerator:
    def __init__(self, config=None):
        """初始化故事生成器"""
        self.config = config or {}
        self.client = self.create_client()
        
    def create_client(self):
        """创建OpenAI客户端"""
        # 硬编码的API密钥
        api_key = "b8fa9da4-5c3a-4617-b17e-ff0cb092627f"
        
        client = OpenAI(
            # 配置API端点
            base_url="https://ark.cn-beijing.volces.com/api/v3",
            api_key=api_key,
        )
        
        return client
    
    def generate_story(self, story_params):
        """生成儿童故事"""
        # 提取故事参数
        theme = story_params.get('theme', '')
        main_character = story_params.get('main_character', '')
        setting = story_params.get('setting', '')
        moral = story_params.get('moral', '')
        
        # 构建故事生成提示
        prompt = self._build_story_prompt(theme, main_character, setting, moral)
        
        try:
            # 使用非流式请求生成故事
            completion = self.client.chat.completions.create(
                model="ep-20251001204558-gqnb8",
                messages=[
                    {"role": "system", "content": "你是一个儿童故事作家，擅长创作温馨、有趣且富有教育意义的儿童故事。"},
                    {"role": "user", "content": prompt},
                ],
            )
            
            story_content = completion.choices[0].message.content
            return story_content
            
        except Exception as e:
            print(f"故事生成出错: {e}")
            # 返回一个简单的示例故事作为备用
            return f"这是一个关于{main_character}在{setting}的故事，主题是{theme}。故事讲述了{main_character}经历的一次奇妙冒险。"
    
    def _build_story_prompt(self, theme, main_character, setting, moral):
        """构建故事生成的提示词"""
        prompt = f"请创作一个适合3-6岁儿童阅读的故事，要求如下：\n"
        prompt += f"1. 主题：{theme}\n"
        prompt += f"2. 主角：{main_character}\n"
        prompt += f"3. 背景：{setting}\n"
        
        if moral:
            prompt += f"4. 寓意：{moral}\n"
            
        prompt += "\n请确保故事内容温馨、有趣、语言简单易懂，并适合朗读给儿童听。故事长度适中，不要太长。"
        
        return prompt
        
    def save_story(self, story_content, filename="story.txt", folder="output"):
        """保存故事到文件"""
        try:
            # 确保文件夹存在
            if not os.path.exists(folder):
                os.makedirs(folder)
                
            # 完整文件路径
            filepath = os.path.join(folder, filename)
            
            # 写入文件
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(story_content)
                
            return filepath
        except Exception as e:
            print(f"保存故事失败: {e}")
            return None